package feng.demo.service;

import feng.demo.dao.BreedDao;
import feng.demo.dao.TypeDao;
import feng.demo.entity.Breed;
import feng.demo.entity.Commodity;
import feng.demo.entity.Type;
import feng.demo.entity.Types;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
public class TypeServiceImpl implements TypeService{
    @Autowired
    TypeDao typeDao;
    @Autowired
   BreedService breedService;
    @Autowired
    CommodityService commodityService;
    @Override
    public List<Type> findAll() {
        List<Type> types = typeDao.findAll();
        return doadds(types);
    }

    @Override
    public Type findById(Integer typeid) {
        Type type = typeDao.findById(typeid);
        return doadd(type);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int add(Type type) {
        int add = typeDao.add(type);
        Breed breed = type.getBreed();
        breed.setNum(1);
        breedService.update(breed);
        return add;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int del(Integer typeid) {
        Type type = typeDao.findById(typeid);
        Breed breed = type.getBreed();
        breed.setNum(-1);
        breedService.update(breed);
        int del = typeDao.del(typeid);
        return del;
    }

    @Override
    public int update(Type type) {
        return typeDao.update(type);
    }

    @Override
    public List<Type> findByBreedId(Integer breedid) {
        List<Type> list = typeDao.findByBreedId(breedid);
        return doadds(list);
    }

    @Override
    public List<Type> findAllLimit(Integer pagenum, Integer lines) {
        List<Type> list = typeDao.findAllLimit(pagenum, lines);
        return doadds(list);
    }

    @Override
    public List<Types> findAlls() {
        List<Types> list = typeDao.findAlls();
        return doaddss(list);
    }

    @Override
    public int findCount() {
        return typeDao.findCount();
    }

    private  List<Types> doaddss(List<Types>list){
        for (Types t:list) {
            Breed breed = breedService.findById(t.getBreed().getBreedid());
            List<Commodity> commodities = commodityService.findByTypeid(t.getTypeid());
            t.setBreed(breed);
            t.setCommoditiys(commodities);
        }
        return list;
    }

    private List<Type> doadds(List<Type> list){
        for (Type t:list) {
            Breed breed = breedService.findById(t.getBreed().getBreedid());
            t.setBreed(breed);
        }
        return list;

    }
    private Type doadd(Type t){
        Breed breed = breedService.findById(t.getBreed().getBreedid());
        t.setBreed(breed);
        return t;
    }
}
